package com.yztc.xiami_app.ui.activity.goodsdetails;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.yztc.xiami_app.R;
import com.yztc.xiami_app.bean.goodsdetails.GoodsDetailsBean;
import com.yztc.xiami_app.bean.shopcart.ShopCart;
import com.yztc.xiami_app.constant.OtherConstant;
import com.yztc.xiami_app.constant.URLConstant;
import com.yztc.xiami_app.ui.goodsdetail.presenter.GoodsDetailsPresenterImpl;
import com.yztc.xiami_app.ui.goodsdetail.presenter.IGoodsDetailsPresenter;
import com.yztc.xiami_app.ui.goodsdetail.view.IGoodsDetailsView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;


/**
 * 展示“商品详情”的页面
 */
public class GoodsDetailsActivity extends AppCompatActivity implements IGoodsDetailsView {

    @BindView(R.id.details_goods_name_tv)
    TextView detailsGoodsNameTv; //商品名称
    @BindView(R.id.details_goods_price_tv)
    TextView detailsGoodsPriceTv;//商品价格
    @BindView(R.id.describe_tv)
    TextView describeTv; //商品属性的描述
    @BindView(R.id.layout_details_main)
    LinearLayout detailsMainLayout; //详情界面主布局
    @BindView(R.id.shop_cart_btn)
    Button shopCartBtn;//加入购物车按钮
    @BindView(R.id.buy_now_btn)
    Button buyNowBtn;//加入购物车按钮
    @BindView(R.id.details_toolBar)
    Toolbar toolBar;
    @BindView(R.id.detail_goods_name_title_tv)
    TextView detailGoodsNameTitleTv; //商品名称的标题的提示
    @BindView(R.id.details_goods_price_title_tv)
    TextView detailsGoodsPriceTitleTv; //商品价格的标题的提示
    @BindView(R.id.detail_fixed_iv)
    ImageView detailFixedIv; //固定的服务的图片
    @BindView(R.id.detail_load_error_tv)
    TextView detailLoadErrorTv; //加载错误时的提示信息
    @BindView(R.id.cardView1)
    CardView cardView1;
    @BindView(R.id.cardView2)
    CardView cardView2;
    @BindView(R.id.cardView3)
    CardView cardView3;

    private String url;


    private Context mContext;
    private IGoodsDetailsPresenter mGoodsDetailsPresenter;
    private List<String> shopPicList = new ArrayList<>(); //商品图片的Url地址的集合
    private String productId; //商品ID，也就是订单号
    private int price; //商品价格
    private String productName; //商品名称
    private int num; //商品数量


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);

        ButterKnife.bind(this);


        mContext = this;
        //初始化Presenter对象
        mGoodsDetailsPresenter = new GoodsDetailsPresenterImpl(this);

        initToolBar();
        getProductId();


    }


    private void initToolBar() {
        setSupportActionBar(toolBar);
    }

    //加载菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_share, menu);
        return true;
    }

    //选择菜单
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.menu_share:
                final UMImage image = new UMImage(GoodsDetailsActivity.this, url);

                new ShareAction(GoodsDetailsActivity.this).setPlatform(SHARE_MEDIA.QQ)
                        .withText("XiaMi_APP")
                        .withMedia(image)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {
                            }
                        }).share();
                break;
        }
        return true;
    }

    //获取首页传递的产品的ID
    private void getProductId() {
        Intent intent = getIntent();
        int productId = intent.getIntExtra(OtherConstant.KEY_PRODUCTID, 0);
        Log.i("tag", "productId--------->" + productId);
        loadGoodsDetailsData(productId);
    }

    //加载商品详情页面所需的数据
    private void loadGoodsDetailsData(int productId) {
        mGoodsDetailsPresenter.getGoodsDetailsBean(productId + "", URLConstant.URL_GOODS_DETAIL_BASE);
    }


    //显示商品详情的数据
    @Override
    public void showGoodsDetails(GoodsDetailsBean goodsDetailsBean) {

        showData(goodsDetailsBean);
    }

    //加载错误
    @Override
    public void loadError() {
        Toast.makeText(mContext, "该商品暂无库存", Toast.LENGTH_SHORT).show();
        detailGoodsNameTitleTv.setVisibility(View.GONE); //设置不可见
        detailsGoodsPriceTitleTv.setVisibility(View.GONE); //设置不可见
        shopCartBtn.setVisibility(View.GONE); //设置不可见
        buyNowBtn.setVisibility(View.GONE); //设置不可见
        detailFixedIv.setVisibility(View.GONE); //设置不可见
        detailLoadErrorTv.setVisibility(View.GONE); //设置可见
        cardView1.setVisibility(View.GONE);
        cardView2.setVisibility(View.GONE);
        cardView3.setVisibility(View.GONE);
    }

    private void showData(GoodsDetailsBean goodsDetailsBean) {
        productName = goodsDetailsBean.getRp_result().getProductName(); //产品名称
        //一个包含推荐商品等信息的WebView的地址
        String shareurl = goodsDetailsBean.getRp_result().getShareurl();
        //商品价格
        price = goodsDetailsBean.getRp_result().getSecooPrice();
        //获取商品的很长的名字以及图片的详情展示
        List<GoodsDetailsBean.RpResultBean.DetailDescBean> descBeanList = goodsDetailsBean.getRp_result().getDetailDesc();
        //获取商品属性的名称和值的对象的集合
        List<GoodsDetailsBean.RpResultBean.ProductExtraPpropertysBean> productExtraPpropertyList = goodsDetailsBean.getRp_result().getProductExtraPpropertys();
        //商品id，也就是订单号
        productId = productExtraPpropertyList.get(0).getPropertyValue();
        //设置商品名称
        detailsGoodsNameTv.setText(productName);
        //设置商品价格
        detailsGoodsPriceTv.setText("¥" + price);

        StringBuffer buffer = new StringBuffer(); //存储商品属性的缓冲区
        for (int i = 0; i < productExtraPpropertyList.size(); i++) {
            String propertyName = productExtraPpropertyList.get(i).getPropertyName(); //属性名称
            String propertyValue = productExtraPpropertyList.get(i).getPropertyValue(); //属性的值
            Log.i("tag", "---->" + propertyName + ":" + propertyValue);
            buffer.append(propertyName).append(":").append(propertyValue).append("\n\n");
        }
        //设置商品的属性
        describeTv.setText(buffer.toString());

        //动态设置商品图片
        for (int i = 0; i < descBeanList.size(); i++) {
            //获取类型
            int type = descBeanList.get(i).getType();
            if (type == 1) {
                //类型为图片的Url地址
                String picUrl = descBeanList.get(i).getUrl(); //获取展示的图片的地址
                url = picUrl;
                shopPicList.add(picUrl); //把地址添加到List集合，以便传递给购物车的Dialog
                //动态生成ImageView
                ImageView iv = new ImageView(mContext);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(550, 550);
                layoutParams.setMargins(200, 10, 10, 10);
                iv.setLayoutParams(layoutParams); //设置图片的宽高
                iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE); //设置拉伸方式
                Glide.with(mContext).load(picUrl).into(iv); //Glide加载商品图片
                detailsMainLayout.addView(iv);
            }
        }
    }

    @OnClick({R.id.shop_cart_btn, R.id.buy_now_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shop_cart_btn:
                //加入购物车按钮,打开购物车的Dialog
                showShopCart();
                break;
            case R.id.buy_now_btn:
                //立即购买按钮
                break;
        }
    }

    //显示购物车的Dialog
    private void showShopCart() {
        View dialogView = getLayoutInflater().inflate(R.layout.custom_shop_cart_dialog, null);
        ImageView goodsIv = (ImageView) dialogView.findViewById(R.id.shop_cart_goods_iv); //购物车中的商品图片
        TextView goodsPrice = (TextView) dialogView.findViewById(R.id.shop_cart_goods_price_tv); //购物车中商品价格
        ImageView closeShopCart = (ImageView) dialogView.findViewById(R.id.shop_cart_close_iv); //关闭购物车的Icon
        ImageView minusIv = (ImageView) dialogView.findViewById(R.id.shop_cart_goods_num_minus); //减号
        ImageView plusIv = (ImageView) dialogView.findViewById(R.id.shop_cart_goods_num_plus); //加号
        final TextView goodsNumTv = (TextView) dialogView.findViewById(R.id.shop_cart_goods_num_tv); //商品数量的值
        Button addToShopCartBtn = (Button) dialogView.findViewById(R.id.shop_cart_buy_tv); //加入购物车按钮

        String shopCartGoodsUrl = shopPicList.get(0); //购物车Dialog界面的商品图片的Url地址
        Glide.with(mContext).load(shopCartGoodsUrl).into(goodsIv); //设置购物车中的商品的图片
        goodsPrice.setText("¥" + price); //设置购物车中的商品价格
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        final AlertDialog dialog = builder.setView(dialogView)
                .create();
        dialog.setCanceledOnTouchOutside(false); //设置点击Dialog外部区域，不能让Dialog消失
        dialog.show(); //显示
        closeShopCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击图标，关闭购物车Dialog
                dialog.dismiss();
            }
        });
        //减少数量
        minusIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //商品数量减1
                //获取当前的默认的商品的数量
                num = Integer.parseInt(goodsNumTv.getText().toString());
                if (num < 1) {
                    return;
                }
                num--;
                //重新设置商品数量的值
                goodsNumTv.setText(String.valueOf(num));
            }
        });
        //增加数量
        plusIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //商品数量加1
                //获取当前的默认的商品的数量
                num = Integer.parseInt(goodsNumTv.getText().toString());
                if (num > 99) {
                    return;
                }
                num++;
                //重新设置商品数量的值
                goodsNumTv.setText(String.valueOf(num));
            }
        });
        //商品数量的增加减少的点击事件
        //加入购物车按钮的点击事件
        addToShopCartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //加入购物车操作
                ShopCart shopCart = new ShopCart(productId, shopPicList.get(0), productName, price, num);
                //把购物车对象，保存到Bmob云数据库
                shopCart.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {
                            Toast.makeText(mContext, "添加商品成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss(); //对话框消失
                        } else {
                            Toast.makeText(mContext, "添加商品失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }
}
